package com.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.app.dao.zl.ZlMapper;
import com.app.domain.*;
import com.app.domain.response.GenericResponse;
import com.app.domain.zl.*;
import com.app.service.UploadService;
import com.app.service.ZlService;
import com.app.utils.TimeHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ZlServiceImpl implements ZlService {
    @Autowired
    ZlMapper zlMapper;

    @Autowired
    UploadService uploadService;

    @Value("${zl.addZhanglaHost}")
    private String addZhanglaHost;
    @Value("${zl.zhanglaSAddListHost}")
    private String zhanglaSAddListHost;
    @Value("${zl.zhanglaSSAddListHost}")
    private String zhanglaSSAddListHost;
    @Value("${zl.editService}")
    private String editService;
    @Value("${zl.rwdService}")
    private String rwdService;

    @Value("${zl.shebeibianhao}")
    private String shebeibianhao;

    // 缓存任务单信息，避免重复获取任务单列表
    private static Map<String, String> rwdCache = null;
    // 缓存上次更新时间，用于定期刷新缓存
    private static Long rwdCacheTime = null;
    // 缓存有效期（毫秒），设置为1小时
    private static final long CACHE_EXPIRE_TIME = 60 * 60 * 1000;

    @Override
    public List<ZljlInfo> queryZljlInfoPage(String searchIsAll) {
        return zlMapper.queryZljlInfoPage(searchIsAll);
    }

    @Override
    public List<ZljlData> findAllZljlData() {
        return zlMapper.findAllZljlData();
    }

    @Override
    public void updateUploadedById(String uploaded, Integer zljlInfoId) {
        zlMapper.updateUploadedById(uploaded, zljlInfoId);
    }

    @Override
    public ZljlInfo queryZljlInfoById(int id) {
        return zlMapper.queryZljlInfoById(id);
    }

    @Override
    public List<ZljlData> findZljlDataByQlbh(String qlbh) {
        return zlMapper.findZljlDataByQlbh(qlbh);
    }

    @Override
    public List<ZljlRealData> queryZljlRealData(String qlbh, String gsbh) {
        return zlMapper.queryZljlRealData(qlbh, gsbh);
    }

    @Override
    public boolean uploadSingleHoleData(ZljlInfo zljlInfo, ZljlData zljlData, String shebeibianhao) {
        String targetQlbh = zljlInfo.getQlbh();
        String selectedRwd = null;
        String selectedText = null;

        try {
            log.info("开始上传孔数据，梁号:{}，孔号:{}", targetQlbh, zljlData.getGsbh());

            // 获取任务单列表（带缓存机制）
            Map<String, String> resultMap = getRwdListWithCache();

            // 检查缓存中是否存在该梁号对应的任务单
            boolean beamRwdExists = findRwdForBeam(resultMap, targetQlbh);

            // 如果缓存中没有找到对应的任务单，尝试刷新缓存后再次查找
            if (!beamRwdExists) {
                log.info("在缓存中未找到梁号 {} 对应的任务单，尝试刷新缓存", targetQlbh);
                // 清除缓存并重新获取
                clearRwdCache();
                resultMap = getRwdListWithCache();
                // 再次检查刷新后的缓存
                beamRwdExists = findRwdForBeam(resultMap, targetQlbh);
            }

            if (resultMap != null && beamRwdExists) {
                // 提前分割targetQlbh以提高性能并避免重复分割
                String[] split = targetQlbh.split("\\|");
                boolean hasValidSplit = split.length >= 2;

                for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                    String gongdanName = entry.getKey();  // 工单名称
                    String gongdanId = entry.getValue();  // 工单号(uuid)

                    // 添加空值检查
                    if (gongdanName == null) {
                        continue;
                    }

                    // 首先尝试直接匹配梁号
                    if (gongdanName.contains(targetQlbh)) {
                        selectedRwd = gongdanId;  // 找到对应的工单号
                        selectedText = gongdanName;
                        break;  // 找到后可以提前退出循环
                    }

                    // 如果直接匹配失败且targetQlbh可以被正确分割，尝试分割匹配
                    if (hasValidSplit && gongdanName.contains(split[0].trim()) && gongdanName.contains(split[1].trim())) {
                        selectedRwd = gongdanId;  // 找到对应的工单号
                        selectedText = gongdanName;
                        break;  // 找到后可以提前退出循环
                    }
                }
            }
        } catch (Exception e) {
            // 记录异常日志，返回错误响应
            log.error("获取任务单列表失败，梁号:" + targetQlbh + "，孔号:" + zljlData.getGsbh(), e);
            return false;
        }

        if (selectedRwd == null) {
            log.warn("未获取到梁号对应工单号，梁号:{}", targetQlbh);
            return false;
        }

        try {
            // 检查该梁是否已有上传的孔道，如果有则使用相同的syjid，否则生成新的
            String syjid = generateSyjid(zljlInfo);
            log.info("使用批次ID: {}", syjid);

            // 生成孔数据唯一标识
            String fguid = UUID.randomUUID().toString().replace("-", "");
            log.info("为孔号{}生成唯一标识: {}", zljlData.getGsbh(), fguid);

            TensionProjectInfo tensionProjectInfo = getTensionProjectInfo(zljlInfo, zljlData, shebeibianhao, selectedRwd, selectedText, syjid, fguid);
            Map<String, Object> maps = getTensionMainData(zljlInfo, zljlData, syjid, fguid, shebeibianhao, selectedRwd, selectedText);
            List<TensionMainData> tensionMainDataList = (List<TensionMainData>) maps.get("tensionMainDataList");
            List<TensionSubData> tensionSubDataList = (List<TensionSubData>) maps.get("tensionSubDataList");
            List<TensionCurveData> tensionCurveDataList = (List<TensionCurveData>) maps.get("tensionCurveDataList");
            tensionProjectInfo.setZhanglam(tensionMainDataList);

            // 准备上传数据
         /*   String jsonString = JSON.toJSONString(tensionProjectInfo);
            String jsonString1 = JSON.toJSONString(tensionSubDataList);
            String jsonString2 = JSON.toJSONString(tensionCurveDataList);*/

            // 处理"终"孔的fguid
            if (zljlData.getGsbh().contains("终")) {
                if (tensionMainDataList != null && !tensionMainDataList.isEmpty()) {
                    fguid = tensionMainDataList.get(0).getFguid();
                    log.info("更新终孔fguid为: {}", fguid);
                }
            }

            // 检查是否已有部分上传记录
            ZljlDataUploadStatus existingStatus = findZljlDataUploadStatusByZljlDataId(zljlData.getId());
            if (existingStatus != null) {
                // 如果已有上传记录，则根据记录决定是否需要重新上传
                if ("1".equals(existingStatus.getUploadedFlag())) {
                    log.info("孔数据已成功上传，无需重复上传，梁号:{}，孔号:{}", zljlInfo.getQlbh(), zljlData.getGsbh());
                    return true;
                }

                // 如果主数据已上传，则不再重复上传
                if ("1".equals(existingStatus.getMainDataStatus())) {
                    tensionProjectInfo.setAllowOverride(false);
                }

                // 如果子数据已上传，则不再重复上传
                if ("1".equals(existingStatus.getSubDataStatus())) {
                    tensionSubDataList.clear();
                }

                // 如果曲线数据已部分或全部上传，则只上传未上传的部分
                if ("1".equals(existingStatus.getCurveDataStatus()) ||
                    "2".equals(existingStatus.getCurveDataStatus())) {
                    // 计算需要上传的曲线数据
                    int uploadedCount = existingStatus.getUploadedCurveCount();
                    if (uploadedCount < tensionCurveDataList.size()) {
                        tensionCurveDataList = tensionCurveDataList.subList(uploadedCount, tensionCurveDataList.size());
                        log.info("部分曲线数据已上传，剩余{}条需要上传", tensionCurveDataList.size());
                    } else {
                        tensionCurveDataList.clear();
                        log.info("所有曲线数据已上传完毕");
                    }
                }
            }



            // 执行数据上传
            ZljlDataUploadStatus uploadStatus = performDetailedDataUpload(tensionProjectInfo, tensionSubDataList, tensionCurveDataList);

            if (uploadStatus != null && uploadStatus.getUploadedFlag() != null) {
                // 设置额外的字段
                uploadStatus.setZljlDataId(zljlData.getId());
                uploadStatus.setSyjid(syjid);
                uploadStatus.setFguid(fguid);
                uploadStatus.setUploadTime(TimeHelper.getCurrentTime());

                // 更新详细上传状态
                updateDetailedUploadStatus(uploadStatus);

                // 只有当主数据、子数据和曲线数据都成功上传时，才认为上传成功
                if ("1".equals(uploadStatus.getUploadedFlag())) {
                    // 插入上传记录
                    TensionUploadRecord record = new TensionUploadRecord();
                    record.setSyjid(syjid);
                    record.setFguid(fguid);
                    record.setQlbh(zljlInfo.getQlbh());
                    record.setGsbh(zljlData.getGsbh());
                    record.setUploadTime(TimeHelper.getCurrentTime());
                    record.setStatus("1");
                    insertUploadRecord(record);
                    log.info("插入上传记录，梁号:{}，孔号:{}", zljlInfo.getQlbh(), zljlData.getGsbh());

                    // 检查是否所有孔都已上传完成
                    checkAndMarkZljlInfoAsComplete(zljlInfo, selectedRwd);

                    log.info("孔数据上传完成，梁号:{}，孔号:{}", zljlInfo.getQlbh(), zljlData.getGsbh());
                    return true;
                } else {
                    log.warn("孔数据部分上传成功，梁号:{}，孔号:{}，上传状态:{}",
                            zljlInfo.getQlbh(), zljlData.getGsbh(), uploadStatus.getUploadedFlag());
                    // 对于部分上传成功的情况，我们仍然返回false，以便任务可以重试
                    return false;
                }
            } else {
                log.warn("孔数据上传失败，梁号:{}，孔号:{}", zljlInfo.getQlbh(), zljlData.getGsbh());
                return false;
            }
        } catch (Exception e) {
            log.error("上传单个孔数据失败，梁号:" + zljlInfo.getQlbh() + "，孔号:" + zljlData.getGsbh(), e);
            return false;
        }
    }

    /**
     * 执行实际的数据上传操作
     *
     * @param tensionProjectInfo   项目信息
     * @param tensionSubDataList   子数据列表
     * @param tensionCurveDataList 曲线数据列表
     * @return 上传是否成功
     */
    private boolean performDataUpload(TensionProjectInfo tensionProjectInfo, List<TensionSubData> tensionSubDataList, List<TensionCurveData> tensionCurveDataList) {
        return performDetailedDataUpload(tensionProjectInfo, tensionSubDataList, tensionCurveDataList) != null;
    }

    /**
     * 执行实际的数据上传操作，并返回详细的上传状态
     *
     * @param tensionProjectInfo   项目信息
     * @param tensionSubDataList   子数据列表
     * @param tensionCurveDataList 曲线数据列表
     * @return 上传状态对象，如果上传过程中发生严重错误则返回null
     */
    private ZljlDataUploadStatus performDetailedDataUpload(TensionProjectInfo tensionProjectInfo, List<TensionSubData> tensionSubDataList, List<TensionCurveData> tensionCurveDataList) {
        ZljlDataUploadStatus status = new ZljlDataUploadStatus();
        status.setMainDataStatus("0"); // 未上传
        status.setSubDataStatus("0");  // 未上传
        status.setCurveDataStatus("0"); // 未上传
        status.setTotalCurveCount(tensionCurveDataList.size());
        status.setUploadedCurveCount(0);

        try {
            log.debug("准备上传数据到远程服务器");

            // 上传项目主数据
            if (tensionProjectInfo.isAllowOverride()) {
                GenericResponse pResult = uploadService.sendMessage(addZhanglaHost, JSON.toJSONString(tensionProjectInfo));
                if (!isSuccess(pResult)) {
                    log.warn("上传项目主数据失败: {}", pResult != null ? pResult.getMessage() : "未知错误");
                    status.setMainDataStatus("2"); // 上传失败
                    return status;
                }
                status.setMainDataStatus("1"); // 上传成功
                log.debug("项目主数据上传成功");
            } else {
                status.setMainDataStatus("1"); // 已上传
                log.debug("项目主数据已上传，跳过");
            }

            // 上传子数据
            if (!tensionSubDataList.isEmpty()) {
                MainTrZhanglaS mainTrZhanglaS = new MainTrZhanglaS();
                mainTrZhanglaS.setTrZhanglaS(tensionSubDataList);
                GenericResponse sResult = uploadService.sendMessage(zhanglaSAddListHost, JSON.toJSONString(mainTrZhanglaS));
                if (!isSuccess(sResult)) {
                    log.warn("上传子数据失败: {}", sResult != null ? sResult.getMessage() : "未知错误");
                    status.setSubDataStatus("2"); // 上传失败
                    return status;
                }
                status.setSubDataStatus("1"); // 上传成功
                log.debug("子数据上传成功");
            } else {
                status.setSubDataStatus("1"); // 已上传或无需上传
                log.debug("子数据无需上传");
            }

            // 分批上传曲线数据（每批30条）
            int totalCurveData = tensionCurveDataList.size();
            if (totalCurveData > 0) {
                int batchSize = 30;
                int uploadedCurveCount = 0;
                boolean hasPartialCurveUploadFailure = false;

                for (int i = 0; i < totalCurveData; i += batchSize) {
                    int endIndex = Math.min(i + batchSize, totalCurveData);
                    List<TensionCurveData> batch = tensionCurveDataList.subList(i, endIndex);
                    MainTrZhanglaSS mainTrZhanglaSS = new MainTrZhanglaSS();
                    mainTrZhanglaSS.setTrZhanglaSS(batch);

                    GenericResponse cResult = uploadService.sendMessage(zhanglaSSAddListHost, JSON.toJSONString(mainTrZhanglaSS));
                    if (!isSuccess(cResult)) {
                        log.warn("上传曲线数据失败，批次 {}-{}: {}", i, endIndex, cResult != null ? cResult.getMessage() : "未知错误");
                        hasPartialCurveUploadFailure = true;
                        // 继续尝试上传其他批次而不是直接返回失败
                    } else {
                        uploadedCurveCount += batch.size();
                        log.debug("曲线数据上传成功，批次 {}-{}", i, endIndex);
                    }
                }

                status.setUploadedCurveCount(uploadedCurveCount);

                if (hasPartialCurveUploadFailure) {
                    if (uploadedCurveCount > 0) {
                        status.setCurveDataStatus("2"); // 部分上传
                        log.warn("曲线数据部分上传失败，但主数据和子数据已成功上传，成功上传 {} 条曲线数据", uploadedCurveCount);
                    } else {
                        status.setCurveDataStatus("3"); // 全部失败
                        log.warn("曲线数据全部上传失败，但主数据和子数据已成功上传");
                    }
                } else {
                    status.setCurveDataStatus("1"); // 全部上传成功
                    log.info("所有曲线数据上传成功，总计: {} 条", totalCurveData);
                }
            } else {
                status.setCurveDataStatus("1"); // 已上传或无需上传
                status.setUploadedCurveCount(0);
                status.setTotalCurveCount(0);
                log.debug("曲线数据无需上传");
            }

            // 设置上传标识
            if ("1".equals(status.getMainDataStatus()) && "1".equals(status.getSubDataStatus())) {
                // 主数据和子数据都上传成功
                if ("1".equals(status.getCurveDataStatus())) {
                    // 所有数据都上传成功
                    status.setUploadedFlag("1");
                } else {
                    // 主数据和子数据成功，但曲线数据部分失败
                    status.setUploadedFlag("2");
                }
            }

            return status;

        } catch (Exception e) {
            log.error("执行数据上传时发生异常", e);
            return null;
        }
    }

    private boolean isSuccess(GenericResponse result) {
        return result != null && result.getSuccess();
    }

    /**
     * 更新孔道上传的详细状态
     *
     * @param status 上传状态对象
     */
    private void updateDetailedUploadStatus(ZljlDataUploadStatus status) {
        ZljlDataUploadStatus existingStatus = findZljlDataUploadStatusByZljlDataId(status.getZljlDataId());
        if (existingStatus != null) {
            // 更新现有状态
            existingStatus.setUploadedFlag(status.getUploadedFlag());
            existingStatus.setUploadTime(status.getUploadTime());
            existingStatus.setSyjid(status.getSyjid());
            existingStatus.setFguid(status.getFguid());
            if (status.getMainDataStatus() != null) {
                existingStatus.setMainDataStatus(status.getMainDataStatus());
            }
            if (status.getSubDataStatus() != null) {
                existingStatus.setSubDataStatus(status.getSubDataStatus());
            }
            if (status.getCurveDataStatus() != null) {
                existingStatus.setCurveDataStatus(status.getCurveDataStatus());
            }
            // 累加已上传的曲线数据数量
            if (status.getUploadedCurveCount() > 0) {
                existingStatus.setUploadedCurveCount(existingStatus.getUploadedCurveCount() + status.getUploadedCurveCount());
            }
            if (status.getTotalCurveCount() > 0) {
                existingStatus.setTotalCurveCount(status.getTotalCurveCount());
            }
            updateZljlDataUploadStatus(existingStatus);
        } else {
            // 插入新状态
            insertZljlDataUploadStatus(status);
        }
    }

    public TensionProjectInfo getTensionProjectInfo(ZljlInfo zljlInfo, ZljlData zljlData, String shebeibianhao, String selectedRwd, String selectedText, String syjid, String fguid) {
        TensionProjectInfo busi_zlxxb = new TensionProjectInfo();
        busi_zlxxb.setSyjid(syjid);
        busi_zlxxb.setShebeibianhao(shebeibianhao);
        if (StringUtils.isNotEmpty(selectedText)) {
            busi_zlxxb.setGjbh(selectedText);
        } else {
            busi_zlxxb.setGjbh(zljlInfo.getQlbh());
        }
        busi_zlxxb.setGcmc("诸永预制梁场SG02标");
        busi_zlxxb.setYzlc("诸永预制梁场SG02标");
        busi_zlxxb.setGjmc(zljlInfo.getQlbh());
        busi_zlxxb.setSgsj(zljlInfo.getZlrq());
        busi_zlxxb.setSnsjqd("C50");
        busi_zlxxb.setSnskqd("C50");
        busi_zlxxb.setZly1("A1");
        busi_zlxxb.setYbbh1("250410");
        busi_zlxxb.setBdrq1("2025-05-26 08:30:01");
        busi_zlxxb.setZly2("A2");
        busi_zlxxb.setYbbh2("250409");
        busi_zlxxb.setBdrq2("2025-05-26 10:33:01");
        busi_zlxxb.setZlcsu("0");
        busi_zlxxb.setZlcsk("0");
        busi_zlxxb.setZlcsep("0");
        busi_zlxxb.setZlbwpic("0");
        busi_zlxxb.setKualiang(zljlInfo.getBdmc());
        busi_zlxxb.setScljss("");
        busi_zlxxb.setFmqkms("正常");
        busi_zlxxb.setCbunit("ceshi");
        busi_zlxxb.setJlunit("ceshi");
        busi_zlxxb.setHtbh("ceshi-2");
        busi_zlxxb.setMemo("ceshi");
        busi_zlxxb.setStatus("1");
        busi_zlxxb.setMemo("");
        busi_zlxxb.setZlcsu("0");
        busi_zlxxb.setZlcsk("0");
        busi_zlxxb.setZlcsep("0");
        busi_zlxxb.setZlbwpic("");
        busi_zlxxb.setUuid(selectedRwd);
        busi_zlxxb.setIssend("");

        return busi_zlxxb;
    }


    public Map getTensionMainData(ZljlInfo zljlInfo, ZljlData zljlData, String syjid, String fguid, String shebeibianhao, String selectedRwd, String selectedText) {
        Map<String, List> maps = new HashMap<>();
        List<TensionMainData> tensionMainDataList = new ArrayList<>();
        List<TensionSubData> tensionSubDataList = new ArrayList<>();
        List<TensionCurveData> tensionCurveDataAll = new ArrayList<>();
        if (zljlData.getDing_xz().equals("B")) {
            String known = zljlData.getGsbh();
//            String uuid = UUID.randomUUID().toString().replace("-", "");
            TensionMainData tensionMainData = new TensionMainData();
            if (known.contains("初")) {
                //两阶段张拉
                Map<String, ZljlData> map = new HashMap<>();
                tensionMainData.setFguid(fguid);
                tensionMainData.setSyjid(syjid);
                tensionMainData.setShebeibianhao(shebeibianhao);
                ZljlRealData zljlRralDataGsbhTopOne = zlMapper.getZljlRralDataGsbhTopOne(zljlData.getQlbh(), zljlData.getGsbh());
                String zlrq = zljlRralDataGsbhTopOne.getNowdate().split(" ")[0] + " " + zljlRralDataGsbhTopOne.getNowtime().split(" ")[1];
                tensionMainData.setZlsj(TimeHelper.formatZlrq(zlrq));
                String gsbh = known.replace("初", "");
                tensionMainData.setGsbh(gsbh);
                tensionMainData.setGsgs("6");
                tensionMainData.setTxml("0");
                tensionMainData.setSjzll("0");
                tensionMainData.setHtl("6.0");
                tensionMainData.setZscl("0");
                tensionMainData.setLlscl(zljlData.getSjscz());
                tensionMainData.setYxpc("12");
                tensionMainData.setSclper("0");
                tensionMainData.setWt("正常");
                tensionMainData.setClqk("正常");
                tensionMainData.setMemo("");
                tensionMainData.setHege("合格");
                tensionMainData.setYzlb("10");
                tensionMainData.setCzlb("20");
                tensionMainData.setZzlb("100");
                tensionMainData.setHoleid(fguid); // 孔id
                tensionMainData.setStatus("1"); // 完成状态
                tensionMainData.setJlsj(zljlInfo.getZlrq()); // 记录时间
                tensionMainData.setUuid(selectedRwd); // 张拉任务单号
                tensionMainData.setIssend(""); // 质监局对接
                tensionMainDataList.add(tensionMainData);
                for (int i = 0; i < 3; i++) {
                    tensionSubDataList.add(getTensionSubDataZSplice(zljlData, syjid, fguid, i, "1", gsbh, null));
                }
                for (int i = 4; i < 7; i++) {
                    tensionSubDataList.add(getTensionSubDataZSplice(zljlData, syjid, fguid, i, "1", gsbh, null));
                }
                List<ZljlRealData> zljlRealDataList = zlMapper.queryZljlRealData(zljlData.getQlbh(), known);
                List<TensionCurveData> tensionCurveDataZ = getTensionCurveData(shebeibianhao, fguid, zljlRealDataList, selectedText, "1", gsbh);
                tensionCurveDataAll.addAll(tensionCurveDataZ);
            } else if (known.contains("终")) {
                //获取初阶段数据
                String gsbh = known.replace("终", "");
                String gsbhc = gsbh + "初";
                ZljlData zljlDataC = zlMapper.getZljlDataByQlbhAndGsbh(zljlInfo.getQlbh(), gsbhc);

                ZljlDataUploadStatus status = zlMapper.findZljlDataUploadStatusByZljlDataId(zljlDataC.getId());
                if (status != null && "1".equals(status.getUploadedFlag()) && StringUtils.isNotEmpty(status.getSyjid()) && StringUtils.isNotEmpty(status.getFguid())) {
                    String Fguid = status.getFguid();
                    Map<String, ZljlData> map = new HashMap<>();
                    map.put("50", zljlDataC);
                    map.put("100", zljlData);


                    tensionMainData.setFguid(Fguid);
                    tensionMainData.setSyjid(syjid);
                    tensionMainData.setShebeibianhao(shebeibianhao);
                    ZljlRealData zljlRralDataGsbhTopOne = zlMapper.getZljlRralDataGsbhTopOne(zljlDataC.getQlbh(), zljlDataC.getGsbh());
                    String zlrq = zljlRralDataGsbhTopOne.getNowdate().split(" ")[0] + " " + zljlRralDataGsbhTopOne.getNowtime().split(" ")[1];
                    tensionMainData.setZlsj(TimeHelper.formatZlrq(zlrq));
                    tensionMainData.setGsbh(gsbh);
                    tensionMainData.setGsgs("6");
                    tensionMainData.setTxml("0");
                    tensionMainData.setSjzll(map.get("100").getZc_sjlz());
                    tensionMainData.setHtl("6.0");
                    tensionMainData.setZscl(getJssczaSpliceZ(map));
                    tensionMainData.setLlscl(map.get("100").getSjscz());
                    tensionMainData.setYxpc("12");
                    tensionMainData.setSclper(getPca(getJssczaSpliceZ(map), map.get("100").getSjscz()));
                    tensionMainData.setWt("正常");
                    tensionMainData.setClqk("正常");
                    tensionMainData.setMemo("");
                    tensionMainData.setHege("合格");
                    tensionMainData.setYzlb("10");
                    tensionMainData.setCzlb("20");
                    tensionMainData.setZzlb("100");
                    tensionMainData.setHoleid(Fguid); // 孔id
                    tensionMainData.setStatus("1"); // 完成状态
                    tensionMainData.setJlsj(zljlInfo.getZlrq()); // 记录时间
                    tensionMainData.setUuid(selectedRwd); // 张拉任务单号
                    tensionMainData.setIssend(""); // 质监局对接
                    tensionMainDataList.add(tensionMainData);
                    for (int i = 2; i <= 3; i++) {
                        tensionSubDataList.add(getTensionSubDataZSplice(zljlData, syjid, Fguid, i, "1", gsbh, map));
                    }
                    for (int i = 6; i <= 7; i++) {
                        tensionSubDataList.add(getTensionSubDataZSplice(zljlData, syjid, Fguid, i, "1", gsbh, map));
                    }
                    List<ZljlRealData> zljlRealDataList = zlMapper.findRealDataByQlBhAndGsbh(zljlData.getQlbh(), known);
                    List<TensionCurveData> tensionCurveDataZ = getTensionCurveData(shebeibianhao, Fguid, zljlRealDataList, selectedText, "1", gsbh);
                    tensionCurveDataAll.addAll(tensionCurveDataZ);
                } else {
                    log.warn("孔号为：" + known + "的初阶段数据未上传");
                }

            } else {
                tensionMainData.setFguid(fguid);
                tensionMainData.setSyjid(syjid);
                tensionMainData.setShebeibianhao(shebeibianhao);
                ZljlRealData zljlRralDataGsbhTopOne = zlMapper.getZljlRralDataGsbhTopOne(zljlData.getQlbh(), zljlData.getGsbh());
                String zlrq = zljlRralDataGsbhTopOne.getNowdate().split(" ")[0] + " " + zljlRralDataGsbhTopOne.getNowtime().split(" ")[1];
                tensionMainData.setZlsj(TimeHelper.formatZlrq(zlrq));
                tensionMainData.setGsbh(zljlData.getGsbh());
                tensionMainData.setGsgs("6");
                tensionMainData.setTxml("0");
                tensionMainData.setHtl("6.0");
                tensionMainData.setSjzll(zljlData.getZc_sjlz());
                tensionMainData.setZscl(getJssczaZ(zljlData));
                tensionMainData.setSclper(getPca(getJssczaZ(zljlData), zljlData.getSjscz()));
                tensionMainData.setLlscl(zljlData.getSjscz());
                tensionMainData.setYxpc("12");
                tensionMainData.setWt("正常");
                tensionMainData.setClqk("正常");
                tensionMainData.setMemo("");
                tensionMainData.setHege("合格");
                tensionMainData.setYzlb("10");
                tensionMainData.setCzlb("20");
                tensionMainData.setZzlb("100");

                // 设置缺失的属性
                tensionMainData.setHoleid(fguid); // 孔id
                tensionMainData.setStatus("1"); // 完成状态
                tensionMainData.setJlsj(zljlInfo.getZlrq()); // 记录时间
                tensionMainData.setUuid(selectedRwd); // 张拉任务单号
                tensionMainData.setIssend(""); // 质监局对接
                tensionMainDataList.add(tensionMainData);
                for (int i = 0; i < 6; i++) {
                    tensionSubDataList.add(getTensionSubData(zljlData, syjid, fguid, i, zljlData.getGsbh(), "1"));
                }
                List<ZljlRealData> zljlRealDataList = zlMapper.queryZljlRealData(zljlData.getQlbh(), zljlData.getGsbh());
                List<TensionCurveData> tensionCurveData = getTensionCurveData(shebeibianhao, fguid, zljlRealDataList, selectedText, "1", zljlData.getGsbh());
                tensionCurveDataAll.addAll(tensionCurveData);
            }

        } else if (zljlData.getDing_xz().equals("AB")) {
            TensionMainData tensionMainDataZ = new TensionMainData();
            tensionMainDataZ.setFguid(fguid);
            tensionMainDataZ.setSyjid(syjid);
            tensionMainDataZ.setShebeibianhao(shebeibianhao);
            ZljlRealData zljlRralDataGsbhTopOne = zlMapper.getZljlRralDataGsbhTopOne(zljlData.getQlbh(), zljlData.getGsbh());
            String zlrq = zljlRralDataGsbhTopOne.getNowdate().split(" ")[0] + " " + zljlRralDataGsbhTopOne.getNowtime().split(" ")[1];
            tensionMainDataZ.setZlsj(TimeHelper.formatZlrq(zlrq));
            tensionMainDataZ.setGsbh("Z" + zljlData.getGsbh());
            tensionMainDataZ.setGsgs("6");
            tensionMainDataZ.setTxml("0");
            tensionMainDataZ.setHtl("6.0");
            tensionMainDataZ.setSjzll(zljlData.getZc_sjlz());
            tensionMainDataZ.setZscl(getJssczaZ(zljlData));
            tensionMainDataZ.setSclper(getPca(getJssczaZ(zljlData), zljlData.getSjscz()));
            tensionMainDataZ.setLlscl(zljlData.getSjscz());
            tensionMainDataZ.setYxpc("12");
            tensionMainDataZ.setWt("正常");
            tensionMainDataZ.setClqk("正常");
            tensionMainDataZ.setMemo("");
            tensionMainDataZ.setHege("合格");
            tensionMainDataZ.setYzlb("10");
            tensionMainDataZ.setCzlb("20");
            tensionMainDataZ.setZzlb("100");

            // 设置缺失的属性
            tensionMainDataZ.setHoleid(fguid); // 孔id
            tensionMainDataZ.setStatus("1"); // 完成状态
            tensionMainDataZ.setJlsj(zljlInfo.getZlrq()); // 记录时间
            tensionMainDataZ.setUuid(selectedRwd); // 张拉任务单号
            tensionMainDataZ.setIssend(""); // 质监局对接

            for (int i = 0; i < 6; i++) {
                tensionSubDataList.add(getTensionSubData(zljlData, syjid, fguid, i, "Z" + zljlData.getGsbh(), "1"));
            }
            List<ZljlRealData> zljlRealDataList = zlMapper.queryZljlRealData(zljlData.getQlbh(), zljlData.getGsbh());
            List<TensionCurveData> tensionCurveDataZ = getTensionCurveData(shebeibianhao, fguid, zljlRealDataList, selectedText, "1", "Z" + zljlData.getGsbh());
            tensionCurveDataAll.addAll(tensionCurveDataZ);


            TensionMainData tensionMainDataY = new TensionMainData();
            String fguidY = UUID.randomUUID().toString().replace("-", "");
            tensionMainDataY.setFguid(fguidY);
            tensionMainDataY.setSyjid(syjid);
            tensionMainDataY.setShebeibianhao(shebeibianhao);
//            ZljlRealData zljlRralDataGsbhTopOne = zlMapper.getZljlRralDataGsbhTopOne(zljlData.getQlbh(), zljlData.getGsbh());
//            String zlrq = zljlRralDataGsbhTopOne.getNowdate().split(" ")[0] + " " + zljlRralDataGsbhTopOne.getNowtime().split(" ")[1];
            tensionMainDataY.setZlsj(TimeHelper.formatZlrq(zlrq));
            tensionMainDataY.setGsbh("Y" + zljlData.getGsbh());
            tensionMainDataY.setGsgs("6");
            tensionMainDataY.setTxml("0");
            tensionMainDataY.setHtl("6.0");
            tensionMainDataY.setSjzll(zljlData.getZc_sjlz());
            tensionMainDataY.setZscl(getJssczaY(zljlData));
            tensionMainDataY.setSclper(getPca(getJssczaY(zljlData), zljlData.getSjscz()));
            tensionMainDataY.setLlscl(zljlData.getSjscz());
            tensionMainDataY.setYxpc("12");
            tensionMainDataY.setWt("正常");
            tensionMainDataY.setClqk("正常");
            tensionMainDataY.setMemo("");
            tensionMainDataY.setHege("合格");
            tensionMainDataY.setYzlb("10");
            tensionMainDataY.setCzlb("20");
            tensionMainDataY.setZzlb("100");

            // 设置缺失的属性
            tensionMainDataY.setHoleid(fguidY); // 孔id
            tensionMainDataY.setStatus("1"); // 完成状态
            tensionMainDataY.setJlsj(zljlInfo.getZlrq()); // 记录时间
            tensionMainDataY.setUuid(selectedRwd); // 张拉任务单号
            tensionMainDataY.setIssend(""); // 质监局对接
//            tensionMainDataList.add(tensionMainDataY);
            for (int i = 6; i < 12; i++) {
                tensionSubDataList.add(getTensionSubData(zljlData, syjid, fguidY, i, "Y" + zljlData.getGsbh(), "1"));
            }
//            List<ZljlRealData> zljlRealDataList = zlMapper.queryZljlRealData(zljlData.getQlbh(), zljlData.getGsbh());
            List<TensionCurveData> tensionCurveDataY = getTensionCurveData(shebeibianhao, fguidY, zljlRealDataList, selectedText, "2", "Y" + zljlData.getGsbh());
            tensionCurveDataAll.addAll(tensionCurveDataY);
            tensionMainDataList.add(tensionMainDataZ);
            tensionMainDataList.add(tensionMainDataY);
        }


        maps.put("tensionMainDataList", tensionMainDataList);
        maps.put("tensionSubDataList", tensionSubDataList);
        maps.put("tensionCurveDataList", tensionCurveDataAll);
        return maps;
    }

    private List<TensionCurveData> getTensionCurveData(String shebeibianh, String holeId, List<ZljlRealData> zljlRealDataList, String selectedText, String type, String gsbh) {
        List<TensionCurveData> busiZlsySSData = new ArrayList<>();
        for (ZljlRealData zljlRealData : zljlRealDataList) {
            TensionCurveData busiZlsySS = new TensionCurveData();
            if (type.equals("1")) {
                busiZlsySS.setSsid(UUID.randomUUID().toString().replace("-", ""));
                busiZlsySS.setShebeibianhao(shebeibianh);
                busiZlsySS.setJlsj(zljlRealData.getNowdate().split(" ")[0] + " " + zljlRealData.getNowtime().split(" ")[1].substring(0, 8));
                busiZlsySS.setHoleid(holeId);
                busiZlsySS.setZlcs("1");
                busiZlsySS.setZt1("正常");
                busiZlsySS.setZll1(zljlRealData.getA1yl());
                busiZlsySS.setYy1(getyy(zljlRealData.getA1yl(), "A1"));
                busiZlsySS.setDxc1("0");
                busiZlsySS.setScl1(zljlRealData.getA1wy());
                busiZlsySS.setZt2("正常");
                busiZlsySS.setZll2(zljlRealData.getA2yl());
                busiZlsySS.setYy2(getyy(zljlRealData.getA2yl(), "A2"));
                busiZlsySS.setDxc2("0");
                busiZlsySS.setScl2(zljlRealData.getA2wy());
                busiZlsySS.setHolename(gsbh);
                busiZlsySS.setSname(selectedText);
            } else if (type.equals("2")) {
                busiZlsySS.setSsid(UUID.randomUUID().toString().replace("-", ""));
                busiZlsySS.setShebeibianhao(shebeibianh);
                busiZlsySS.setJlsj(zljlRealData.getNowdate().split(" ")[0] + " " + zljlRealData.getNowtime().split(" ")[1].substring(0, 8));
                busiZlsySS.setHoleid(holeId);
                busiZlsySS.setZlcs("1");
                busiZlsySS.setZt1("正常");
                busiZlsySS.setZll1(zljlRealData.getB1yl());
                busiZlsySS.setYy1(getyy(zljlRealData.getB1yl(), "B1"));
                busiZlsySS.setDxc1("0");
                busiZlsySS.setScl1(zljlRealData.getB1wy());
                busiZlsySS.setZt2("正常");
                busiZlsySS.setZll2(zljlRealData.getB2yl());
                busiZlsySS.setYy2(getyy(zljlRealData.getB2yl(), "B2"));
                busiZlsySS.setDxc2("0");
                busiZlsySS.setScl2(zljlRealData.getB2wy());
                busiZlsySS.setHolename(gsbh);
                busiZlsySS.setSname(selectedText);
            }
            busiZlsySSData.add(busiZlsySS);
        }
        return busiZlsySSData;
    }

    /**
     * 检查并标记梁信息为已完成
     *
     * @param zljlInfo 梁信息
     */
    private void checkAndMarkZljlInfoAsComplete(ZljlInfo zljlInfo, String selectedRwd) {
        try {
            // 查询该梁的计划孔数
            List<Zlrw> zlrwList = zlMapper.queryZlrwListByLh(zljlInfo.getQlbh());
            int plannedHoleCount = zlrwList.size();

            // 查询已完成上传的孔数
            List<ZljlData> finishedHoles = zlMapper.findZljlDataByQlbh(zljlInfo.getQlbh());
            long uploadedHoleCount = finishedHoles.stream()
                    .filter(hole -> {
                        ZljlDataUploadStatus status = zlMapper.findZljlDataUploadStatusByZljlDataId(hole.getId());
                        return status != null && "1".equals(status.getUploadedFlag());
                    })
                    .count();

            // 如果所有孔都已上传完成，则更新梁的上传状态
            if (plannedHoleCount > 0 && uploadedHoleCount == plannedHoleCount) {
                Map<String, String> requestMap = new HashMap<>();
                requestMap.put("uuid", selectedRwd);
                requestMap.put("status", "1");
                requestMap.put("status2", "1");
                requestMap.put("wcstatus", "1");
                GenericResponse mResult = uploadService.putMessage(editService, JSON.toJSONString(requestMap));
                // 使用新的状态值更新梁信息：1表示已上传
                if (isSuccess(mResult)) {
                    zlMapper.updateZljlInfoUploadStatus(zljlInfo.getId(), "1", TimeHelper.getCurrentTime());
                }
            }
        } catch (Exception e) {
            log.error("检查并标记梁信息完成状态时发生异常，梁号: {}", zljlInfo.getQlbh(), e);
        }
    }


    private TensionSubData getTensionSubData(ZljlData zljlData, String syjid, String fguid, int i, String gsbh, String type) {
        TensionSubData busiZlsyS = new TensionSubData();
        String sid = UUID.randomUUID().toString().replace("-", "");
        busiZlsyS.setSid(sid);
        busiZlsyS.setFguid(fguid);
        busiZlsyS.setSyjid(syjid);
        busiZlsyS.setGsbh(gsbh);
        busiZlsyS.setChsj("300");
        busiZlsyS.setStatus("1");
        if (type.equals("1")) {
            if (i == 0) {
                busiZlsyS.setJdbfb("10");
                busiZlsyS.setYbds(getyy(zljlData.getCsa_zllz1(), "A1"));
                busiZlsyS.setJdzll(zljlData.getCsa_zllz1());
                busiZlsyS.setJdscl(zljlData.getCsa_ygsc1());
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getCsa_ygsc1());
            } else if (i == 1) {
                busiZlsyS.setJdbfb("20");
                busiZlsyS.setYbds(getyy(zljlData.getKza_zllz1(), "A1"));
                busiZlsyS.setJdzll(zljlData.getKza_zllz1());
                busiZlsyS.setJdscl(zljlData.getKza_ygsc1());
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getKza_ygsc1());
            } else if (i == 2) {//数据源不同
                busiZlsyS.setJdbfb("100");
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setYbds(getyy(zljlData.getZca_zllz1(), "A1"));
                busiZlsyS.setJdzll(zljlData.getZca_zllz1());
                busiZlsyS.setJdscl(zljlData.getZca_ygsc1());
                busiZlsyS.setDcscl(getJssczaZX(zljlData));
            } else if (i == 3) {//数据源不同
                busiZlsyS.setJdbfb("10");
                busiZlsyS.setYbds(getyy(zljlData.getCsa_zllz2(), "A2"));
                busiZlsyS.setJdzll(zljlData.getCsa_zllz2());
                busiZlsyS.setJdscl(zljlData.getCsa_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getCsa_ygsc2());
            } else if (i == 4) {
                busiZlsyS.setJdbfb("20");
                busiZlsyS.setYbds(getyy(zljlData.getKza_zllz2(), "A2"));
                busiZlsyS.setJdzll(zljlData.getKza_zllz2());
                busiZlsyS.setJdscl(zljlData.getKza_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getKza_ygsc2());
            } else if (i == 5) {
                busiZlsyS.setJdbfb("100");
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(getJssczaZY(zljlData));
                busiZlsyS.setYbds(getyy(zljlData.getZca_zllz2(), "A2"));
                busiZlsyS.setJdzll(zljlData.getZca_zllz2());
                busiZlsyS.setJdscl(zljlData.getZca_ygsc2());
            } else if (i == 6) {
                busiZlsyS.setJdbfb("10");
                busiZlsyS.setYbds(getyy(zljlData.getCsb_zllz1(), "B1"));
                busiZlsyS.setJdzll(zljlData.getCsb_zllz1());
                busiZlsyS.setJdscl(zljlData.getCsb_ygsc1());
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getCsb_ygsc1());
            } else if (i == 7) {
                busiZlsyS.setJdbfb("20");
                busiZlsyS.setYbds(getyy(zljlData.getKzb_zllz1(), "B1"));
                busiZlsyS.setJdzll(zljlData.getKzb_zllz1());
                busiZlsyS.setJdscl(zljlData.getKzb_ygsc1());
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getKzb_ygsc1());
            } else if (i == 8) {//数据源不同
                busiZlsyS.setJdbfb("100");
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setYbds(getyy(zljlData.getZcb_zllz1(), "B1"));
                busiZlsyS.setJdzll(zljlData.getZcb_zllz1());
                busiZlsyS.setJdscl(zljlData.getZcb_ygsc1());
                busiZlsyS.setDcscl(getJssczaYX(zljlData));
            } else if (i == 9) {//数据源不同
                busiZlsyS.setJdbfb("10");
                busiZlsyS.setYbds(getyy(zljlData.getCsb_zllz2(), "B2"));
                busiZlsyS.setJdzll(zljlData.getCsb_zllz2());
                busiZlsyS.setJdscl(zljlData.getCsb_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getCsb_ygsc2());
            } else if (i == 10) {
                busiZlsyS.setJdbfb("20");
                busiZlsyS.setYbds(getyy(zljlData.getKzb_zllz2(), "B2"));
                busiZlsyS.setJdzll(zljlData.getKzb_zllz2());
                busiZlsyS.setJdscl(zljlData.getKzb_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getKzb_ygsc2());
            } else if (i == 11) {
                busiZlsyS.setJdbfb("100");
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(getJssczaYY(zljlData));
                busiZlsyS.setYbds(getyy(zljlData.getZcb_zllz2(), "B2"));
                busiZlsyS.setJdzll(zljlData.getZcb_zllz2());
                busiZlsyS.setJdscl(zljlData.getZcb_ygsc2());
            }
        }
        return busiZlsyS;
    }


    private TensionSubData getTensionSubDataZSplice(ZljlData zljlData, String syjid, String fguid, int i, String type, String gsbh, Map<String, ZljlData> map) {
        TensionSubData busiZlsyS = new TensionSubData();
        String sid = UUID.randomUUID().toString().replace("-", "");
        busiZlsyS.setSid(sid);
        busiZlsyS.setFguid(fguid);
        busiZlsyS.setSyjid(syjid);
        busiZlsyS.setGsbh(gsbh);
        busiZlsyS.setChsj("300");
        busiZlsyS.setStatus("1");
        if (type.equals("1")) {

            if (i == 0) {
                busiZlsyS.setJdbfb("10");
                busiZlsyS.setYbds(getyy(zljlData.getCsa_zllz1(), "A1"));
                busiZlsyS.setJdzll(zljlData.getCsa_zllz1());
                busiZlsyS.setJdscl(zljlData.getCsa_ygsc1());
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getCsa_ygsc1());
            } else if (i == 1) {
                busiZlsyS.setJdbfb("20");
                busiZlsyS.setYbds(getyy(zljlData.getKza_zllz1(), "A1"));
                busiZlsyS.setJdzll(zljlData.getKza_zllz1());
                busiZlsyS.setJdscl(zljlData.getKza_ygsc1());
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getKza_ygsc1());
            } else if (i == 2) {//数据源不同
                busiZlsyS.setJdbfb("50");
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getMga_ygsc1());
                busiZlsyS.setYbds(getyy(zljlData.getMga_zllz1(), "A1"));
                busiZlsyS.setJdzll(zljlData.getMga_zllz1());
                busiZlsyS.setJdscl(zljlData.getMga_ygsc1());

            } else if (i == 3) {//数据源不同
                busiZlsyS.setJdbfb("100");
                busiZlsyS.setDh("1");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(getJssczaSpliceZX(map));
                busiZlsyS.setYbds(getyy(map.get("100").getZca_zllz1(), "A1"));
                busiZlsyS.setJdzll(map.get("100").getZca_zllz1());
                busiZlsyS.setJdscl(map.get("100").getZca_ygsc1());

            } else if (i == 4) {//数据源不同
                busiZlsyS.setJdbfb("10");
                busiZlsyS.setYbds(getyy(zljlData.getCsa_zllz2(), "A2"));
                busiZlsyS.setJdzll(zljlData.getCsa_zllz2());
                busiZlsyS.setJdscl(zljlData.getCsa_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getCsa_ygsc2());
            } else if (i == 5) {
                busiZlsyS.setJdbfb("20");
                busiZlsyS.setYbds(getyy(zljlData.getKza_zllz2(), "A2"));
                busiZlsyS.setJdzll(zljlData.getKza_zllz2());
                busiZlsyS.setJdscl(zljlData.getKza_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getKza_ygsc2());
            } else if (i == 6) {
                busiZlsyS.setJdbfb("50");
                busiZlsyS.setYbds(getyy(zljlData.getMga_zllz2(), "A2"));
                busiZlsyS.setJdzll(zljlData.getMga_zllz2());
                busiZlsyS.setJdscl(zljlData.getMga_ygsc2());
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setDcscl(zljlData.getMga_ygsc2());
            } else if (i == 7) {
                busiZlsyS.setJdbfb("100");
                busiZlsyS.setDh("2");
                busiZlsyS.setLjhsl("6.0");
                busiZlsyS.setYbds(getyy(map.get("100").getZca_zllz2(), "A2"));
                busiZlsyS.setJdzll(map.get("100").getZca_zllz2());
                busiZlsyS.setJdscl(map.get("100").getZca_ygsc2());
                busiZlsyS.setDcscl(getJssczaSpliceZY(map));
            }
        }
        return busiZlsyS;
    }


    private static String getyy(String zll, String dh) {
        float aFloat = Float.parseFloat(zll);
        Float f1 = 0f;
        Float f2 = 0f;

        switch (dh) {
            case "A1":
                f1 = 0.03239f;
                f2 = 0.2645f;
                break;
            case "A2":
                f1 = 0.03273f;
                f2 = 0.2524f;
                break;
            case "B1":
                f1 = 0.03272f;
                f2 = 0.4873f;
                break;
            case "B2":
                f1 = 0.03283f;
                f2 = 0.3995f;
                break;
        }
        Float yyf = (f1 * aFloat) + f2;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(yyf);
    }

    @Override
    public List<Zlrw> queryZlrwListByLh(String lh) {
        return zlMapper.queryZlrwListByLh(lh);
    }

    @Override
    public int countFinishedHolesByQlbh(String qlbh) {
        return zlMapper.countFinishedHolesByQlbh(qlbh);
    }

    @Override
    public List<ZljlInfo> findZljlInfoByUploadStatus() {
        return zlMapper.findZljlInfoByUploadStatus();
    }

    @Override
    public void updateZljlInfoUploadStatus(int id, String uploaded, String lastUploadedTime) {
        zlMapper.updateZljlInfoUploadStatus(id, uploaded, lastUploadedTime);
    }

    @Override
    public void updateZljlDataUploadFlag(int id, String uploadedFlag, String uploadTime, String syjid, String fguid) {
        // 保留原有方法，但不再使用
        // zlMapper.updateZljlDataUploadFlag(id, uploadedFlag, uploadTime, syjid, fguid);
    }

    @Override
    public List<ZljlData> findUnuploadedFinishedHoles(String qlbh) {
        // 使用新的方法替代
        return zlMapper.findUnuploadedFinishedHolesWithNewStatus(qlbh);
    }

    @Override
    public void insertUploadRecord(TensionUploadRecord record) {
        zlMapper.insertUploadRecord(record);
    }

    @Override
    public void insertOrUpdateZljlDataUploadStatus(ZljlDataUploadStatus status) {
        // 直接插入记录，因为我们每次都是处理之前未上传的数据
        insertZljlDataUploadStatus(status);
    }

    @Override
    public void insertZljlDataUploadStatus(ZljlDataUploadStatus status) {
        zlMapper.insertZljlDataUploadStatus(status);
    }

    @Override
    public void updateZljlDataUploadStatus(ZljlDataUploadStatus status) {
        zlMapper.updateZljlDataUploadStatus(status);
    }

    @Override
    public ZljlDataUploadStatus findZljlDataUploadStatusByZljlDataId(int zljlDataId) {
        return zlMapper.findZljlDataUploadStatusByZljlDataId(zljlDataId);
    }

    @Override
    public List<ZljlData> findUnuploadedFinishedHolesWithNewStatus(String qlbh) {
        return zlMapper.findUnuploadedFinishedHolesWithNewStatus(qlbh);
    }

    private String getJssczaZX(ZljlData zljlData) {
        float yjd = Float.parseFloat(zljlData.getZca_ygsc1()) - Float.parseFloat(zljlData.getHda_ygsc1());

        //公式
        Float n = (Float.parseFloat(zljlData.getZca_ygsc1()) + Float.parseFloat(zljlData.getKza_ygsc1())) - (2 * Float.parseFloat(zljlData.getCsa_ygsc1())) - yjd;

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    private String getJssczaZY(ZljlData zljlData) {
        float ejd = Float.parseFloat(zljlData.getZca_ygsc2()) - Float.parseFloat(zljlData.getHda_ygsc2());
        //公式
        Float n = (Float.parseFloat(zljlData.getZca_ygsc2()) + Float.parseFloat(zljlData.getKza_ygsc2())) - (2 * Float.parseFloat(zljlData.getCsa_ygsc2())) - ejd;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    private String getJssczaZ(ZljlData zljlData) {
        float yjd = Float.parseFloat(zljlData.getZca_ygsc1()) - Float.parseFloat(zljlData.getHda_ygsc1());
        float ejd = Float.parseFloat(zljlData.getZca_ygsc2()) - Float.parseFloat(zljlData.getHda_ygsc2());
        //公式
        Float n = (Float.parseFloat(zljlData.getZca_ygsc1()) + Float.parseFloat(zljlData.getKza_ygsc1())) - (2 * Float.parseFloat(zljlData.getCsa_ygsc1())) +
                (Float.parseFloat(zljlData.getZca_ygsc2()) + Float.parseFloat(zljlData.getKza_ygsc2())) - (2 * Float.parseFloat(zljlData.getCsa_ygsc2())) - yjd - ejd;

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }


    private String getJssczaYX(ZljlData zljlData) {
        float yjd = Float.parseFloat(zljlData.getZcb_ygsc1()) - Float.parseFloat(zljlData.getHdb_ygsc1());

        //公式
        Float n = (Float.parseFloat(zljlData.getZcb_ygsc1()) + Float.parseFloat(zljlData.getKzb_ygsc1())) - (2 * Float.parseFloat(zljlData.getCsb_ygsc1())) - yjd;

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    private String getJssczaYY(ZljlData zljlData) {
        float ejd = Float.parseFloat(zljlData.getZcb_ygsc2()) - Float.parseFloat(zljlData.getHdb_ygsc2());
        //公式
        Float n = (Float.parseFloat(zljlData.getZcb_ygsc2()) + Float.parseFloat(zljlData.getKzb_ygsc2())) - (2 * Float.parseFloat(zljlData.getCsb_ygsc2())) - ejd;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    private String getJssczaY(ZljlData zljlData) {
        float yjd = Float.parseFloat(zljlData.getZcb_ygsc1()) - Float.parseFloat(zljlData.getHdb_ygsc1());
        float ejd = Float.parseFloat(zljlData.getZcb_ygsc2()) - Float.parseFloat(zljlData.getHdb_ygsc2());
        //公式
        Float n = (Float.parseFloat(zljlData.getZcb_ygsc1()) + Float.parseFloat(zljlData.getKzb_ygsc1())) - (2 * Float.parseFloat(zljlData.getCsb_ygsc1())) +
                (Float.parseFloat(zljlData.getZcb_ygsc2()) + Float.parseFloat(zljlData.getKzb_ygsc2())) - (2 * Float.parseFloat(zljlData.getCsb_ygsc2())) - yjd - ejd;

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }


    /**
     * 两阶段左总和
     *
     * @param map
     * @return
     */
    private String getJssczaSpliceZ(Map<String, ZljlData> map) {
        ZljlData zljlData50 = map.get("50");
        ZljlData zljlData100 = map.get("100");
        float yjd = Float.parseFloat(zljlData100.getZca_ygsc1()) - Float.parseFloat(zljlData100.getHda_ygsc1());
        float ejd = Float.parseFloat(zljlData100.getZca_ygsc2()) - Float.parseFloat(zljlData100.getHda_ygsc2());
        //设置公式
        Float n = (Float.parseFloat(zljlData50.getMga_ygsc1()) + Float.parseFloat(zljlData50.getKza_ygsc1())) - 2 * Float.parseFloat(zljlData50.getCsa_ygsc1()) + (Float.parseFloat(zljlData100.getZca_ygsc1()) - Float.parseFloat(zljlData100.getMga_ygsc1())) +
                (Float.parseFloat(zljlData50.getMga_ygsc2()) + Float.parseFloat(zljlData50.getKza_ygsc2())) - 2 * Float.parseFloat(zljlData50.getCsa_ygsc2()) + (Float.parseFloat(zljlData100.getZca_ygsc2()) - Float.parseFloat(zljlData100.getMga_ygsc2())) - yjd - ejd;
        //保留两位小数点
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    private String getJssczaSpliceZX(Map<String, ZljlData> map) {
        ZljlData zljlData50 = map.get("50");
        ZljlData zljlData100 = map.get("100");
        float yjd = Float.parseFloat(zljlData100.getZca_ygsc1()) - Float.parseFloat(zljlData100.getHda_ygsc1());

        //设置公式
        Float n = (Float.parseFloat(zljlData50.getMga_ygsc1()) + Float.parseFloat(zljlData50.getKza_ygsc1())) - 2 * Float.parseFloat(zljlData50.getCsa_ygsc1()) + (Float.parseFloat(zljlData100.getZca_ygsc1()) - Float.parseFloat(zljlData100.getMga_ygsc1())) - yjd;
        //保留两位小数点
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    private String getJssczaSpliceZY(Map<String, ZljlData> map) {
        ZljlData zljlData50 = map.get("50");
        ZljlData zljlData100 = map.get("100");
        float ejd = Float.parseFloat(zljlData100.getZca_ygsc2()) - Float.parseFloat(zljlData100.getHda_ygsc2());
        //设置公式
        Float n = (Float.parseFloat(zljlData50.getMga_ygsc2()) + Float.parseFloat(zljlData50.getKza_ygsc2())) - 2 * Float.parseFloat(zljlData50.getCsa_ygsc2()) + (Float.parseFloat(zljlData100.getZca_ygsc2()) - Float.parseFloat(zljlData100.getMga_ygsc2())) - ejd;
        //保留两位小数点
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(n);
    }

    /**
     * 生成批次ID
     * 检查该梁是否已有上传的孔道，如果有则使用相同的syjid，否则生成新的
     *
     * @param zljlInfo 梁信息
     * @return 批次ID
     */
    private String generateSyjid(ZljlInfo zljlInfo) {
        String targetQlbh = zljlInfo.getQlbh();

        // 查询已上传的孔道
        List<ZljlData> uploadedHoles = zlMapper.findZljlDataByQlbh(zljlInfo.getQlbh()).stream()
                .filter(hole -> {
                    ZljlDataUploadStatus status = zlMapper.findZljlDataUploadStatusByZljlDataId(hole.getId());
                    return status != null && "1".equals(status.getUploadedFlag());
                })
                .collect(Collectors.toList());

        if (uploadedHoles.isEmpty()) {
            // 没有已上传的孔道，生成新的syjid
            String syjid = "SYJID_" + zljlInfo.getId() + "_" + System.currentTimeMillis();
            log.info("为梁号{}生成新的批次ID: {}", targetQlbh, syjid);
            return syjid;
        } else {
            // 存在已上传的孔道，使用相同的syjid
            ZljlDataUploadStatus status = zlMapper.findZljlDataUploadStatusByZljlDataId(uploadedHoles.get(0).getId());
            String syjid = status.getSyjid();
            log.info("梁号{}使用已有批次ID: {}", targetQlbh, syjid);
            return syjid;
        }
    }

    /**
     * 从工单名称中提取梁号
     *
     * @param gongdanName 工单名称
     * @return 提取的梁号，如果无法提取则返回null
     */
    private String extractQlbhFromGongdanName(String gongdanName) {
        try {
            // 根据示例格式：诸永SG02施工合同段 | K13+100~K25+490K13+100~K25+490工程施工阶段 | K17+976.2~K18+134.4东山吴桥右幅 | 1~3#跨上部构造预制和安装 | 第1跨 | 小箱梁预制 | 右幅第1跨1-1小箱梁 | 预应力筋的加工和张拉
            // 目标梁号应该是：东山吴桥右幅|右幅第1跨1-1小箱梁

            // 检查是否包含示例中的两个部分
            if (gongdanName.contains("东山吴桥右幅") && gongdanName.contains("右幅第1跨1-1小箱梁")) {
                return "东山吴桥右幅|右幅第1跨1-1小箱梁";
            }
        } catch (Exception e) {
            log.warn("从工单名称中提取梁号时发生异常: {}", gongdanName, e);
        }
        return null;
    }

    /**
     * 带缓存机制的任务单列表获取方法
     *
     * @return 任务单列表映射
     */
    private Map<String, String> getRwdListWithCache() {
        // 检查缓存是否存在且未过期
        long currentTime = System.currentTimeMillis();

        if (rwdCache != null &&
                rwdCacheTime != null &&
                (currentTime - rwdCacheTime) < CACHE_EXPIRE_TIME) {
            // 缓存未过期，直接返回缓存数据
            log.debug("使用缓存的任务单列表");
            return rwdCache;
        }

        // 缓存不存在或已过期，重新获取任务单列表
        log.info("重新获取任务单列表");
        Map<String, String> resultMap = null;
        try {
            resultMap = uploadService.getRwdlist(rwdService, shebeibianhao);
        } catch (Exception e) {
            log.error("获取任务单列表时发生异常", e);
        }

        if (resultMap != null) {
            // 更新缓存
            rwdCache = resultMap;
            rwdCacheTime = currentTime;
            log.debug("更新任务单列表缓存");
        }

        return resultMap;
    }

    /**
     * 检查指定梁号是否在任务单列表中存在
     *
     * @param resultMap  任务单列表映射
     * @param beamNumber 梁号
     * @return 是否存在
     */
    private boolean findRwdForBeam(Map<String, String> resultMap, String beamNumber) {
        if (resultMap == null || beamNumber == null) {
            return false;
        }

        // 提前分割beamNumber，避免在循环中重复分割
        String[] split = beamNumber.split("\\|");
        boolean hasValidSplit = split.length >= 2;

        for (String gongdanName : resultMap.keySet()) {
            if (gongdanName == null) {
                continue; // 跳过null值
            }

            // 首先尝试直接匹配
            if (gongdanName.contains(beamNumber)) {
                return true;
            }

            // 如果直接匹配失败且beamNumber可以被正确分割，尝试从工单名称中提取梁号进行匹配
            if (hasValidSplit && gongdanName.contains(split[0].trim()) && gongdanName.contains(split[1].trim())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 清除任务单缓存
     * 在某些情况下可能需要手动清除缓存，例如任务单信息发生重大变化时
     */
    public void clearRwdCache() {
        rwdCache = null;
        rwdCacheTime = null;
        log.info("任务单缓存已清除");
    }

    //计算延伸量误差
    private String getPca(String jssczA, String sjsczStr) {
        Float jsscz = Float.parseFloat(jssczA);
        Float sjscz = Float.parseFloat(sjsczStr);
        Float sclperStr = (jsscz - sjscz) / sjscz;
        sclperStr = sclperStr * 100;
        DecimalFormat decimalFormat = new DecimalFormat("0.000");
        return decimalFormat.format(sclperStr);
    }
}